﻿using Microsoft.EntityFrameworkCore;
using Workflow2211A.Application.Services;
using Workflow2211A.Domain;
using Workflow2211A.Domain.Entities;
using WorkflowCore.Interface;

namespace Workflow2211A.API
{
    public static class WorkflowExtension
    {
        //UseWorkflow ：是对IApplicationBuilder进行扩展的，
        public static void UseWorkflow(this WebApplication app)
        {
            //获取工作流主机
            var workflowHost = app.Services.GetService<IWorkflowHost>();
            //应用程序启动时
            app.Lifetime.ApplicationStarted.Register(() => 
            {
                //开启流程引擎主机
                workflowHost.Start();
                //创建作用域服务提供商
                var serviceProvider = app.Services.CreateScope().ServiceProvider; 
                //获取数据库的服务
                var repository = serviceProvider.GetService<IBaseRepository<WorkflowDefinitionModel>>();
                //获取服务
                var workflowService = serviceProvider.GetService<IWorkflowService>();
                //AsNoTracking:用于指示查询返回的实体不会被上下文跟踪  如果不做
                //ToList 不能乱用，只有当查询结束之后，在统一ToList()
                var list = repository.GetAll().AsNoTracking().ToList();
                
                foreach (var item in list)
                {
                    workflowService.LoadDefinition(item);
                }
            });
            //应用程序结束时
            app.Lifetime.ApplicationStopping.Register(() => 
            {
                //停止流程引擎主机
                workflowHost.Stop();
            });
        }
    }
}
